package com.lib.util;

import cn.hutool.core.bean.BeanUtil;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ResultSetUtil {
    //传对象
    public static void toBean(ResultSet rs, Object o) throws SQLException {
        if(rs==null) {return;}
        //rs中数据集的元数据，列名 等
        ResultSetMetaData md = rs.getMetaData();
        int columnCount = md.getColumnCount();
        Map rowData = null;
        if(rs.next()){
            rowData = new HashMap(columnCount);
            //    System.out.println("=======columnCount="+columnCount);
            for(int i = 1 ; i <= columnCount; i++) {
                //    System.out.println("=====column   i="+i);
                //存入列名  和 列值
                rowData.put(md.getColumnName(i), rs.getObject(i));

            }
        }
        //复制值到对象中
        BeanUtil.copyProperties(rowData,o);
    }
    //传类，  返回对象
    public static <T> T toBean(ResultSet rs, Class<T> tClass ) throws SQLException {
        if(rs==null) {return null;}
        //rs中数据集的元数据，列名 等
        ResultSetMetaData md = rs.getMetaData();
        int columnCount = md.getColumnCount();
        Map rowData = null;
        if(rs.next()){
            rowData = new HashMap(columnCount);
            //     System.out.println("=======columnCount="+columnCount);
            for(int i = 1 ; i <= columnCount; i++) {
                //     System.out.println("=====column   i="+i);
                //存入列名  和 列值
                rowData.put(md.getColumnName(i), rs.getObject(i));

            }
        }
        //复制值到对象中
        return BeanUtil.copyProperties(rowData,tClass);
    }
    public static <T> List<T> toList(ResultSet rs, Class<T> tClass ) throws SQLException {
        if(rs==null) {return null;}
        List<T> list = new ArrayList<>();
        //rs中数据集的元数据，列名 等
        ResultSetMetaData md = rs.getMetaData();
        int columnCount = md.getColumnCount();
        Map rowData = null;
        while(rs.next()){
            rowData = new HashMap(columnCount);
            //   System.out.println("=======columnCount="+columnCount);
            for(int i = 1 ; i <= columnCount; i++) {
                //      System.out.println("=====column   i="+i);
                //存入列名  和 列值
                rowData.put(md.getColumnName(i), rs.getObject(i));

            }
            //复制值到对象中
            list.add(BeanUtil.copyProperties(rowData,tClass));
        }
        return list;
    }
}
